package com.jar.exercise.多线程.AQS.Condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 示例：用ReentrantLock绑定三个条件实现线程A打印一次1，线程B打印两次2，线程C打印三次3
 */
public class Main {
	private int number = 1; // 1 打印一次 2 打印2次 3 打印三次
	private ReentrantLock lock = new ReentrantLock();
	private Condition c1 = lock.newCondition();
	private Condition c2 = lock.newCondition();
	private Condition c3 = lock.newCondition();

	/**
	 * 线程A打印1次
	 * 1.如果number不是1让A线程等待
	 * 2.按照顺序 1-->2 改变number为2
	 */
	void print1() {
		lock.lock();
		try {
			if (number != 1) {
				c1.await(); // 等待A线程
			}
			for (int i = 0; i < number; i++) {
				System.out.println(Thread.currentThread().getName() + (i + 1) + "次");
			}
			number = 2;
			c2.signal(); // 唤醒B线程
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}


	void print2() {
		lock.lock();
		try {
			if (number != 2) {
				c2.await(); // 等待B线程
			}
			for (int i = 0; i < number; i++) {
				System.out.println(Thread.currentThread().getName() + (i + 1) + "次");
			}
			number = 3;
			c3.signal(); // 唤醒C线程
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	void print3() {
		lock.lock();
		try {
			if (number != 3) {
				c3.await(); // 等待C线程
			}
			for (int i = 0; i < number; i++) {
				System.out.println(Thread.currentThread().getName() + (i + 1) + "次");
			}
			number = 1;
			c1.signal(); // 唤醒A线程
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) {
		Main main = new Main();

		Thread A = new Thread(main::print1, "A");
		Thread B = new Thread(main::print2, "B");
		Thread C = new Thread(main::print3, "C");

		A.start();
		B.start();
		C.start();

	}

}
